package com.coder4j.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

import java.util.Objects;

@Slf4j
public class SpringContextUtils {

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    /**
     * 获取应用上下文
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return SpringContextUtils.applicationContext;
    }

    /**
     * 获取环境变量值
     * @param key 键
     * @param defaultValue 默认值
     * @return 值
     */
    public static String getEnvironmentVariableWithDefault(String key, String defaultValue) {
        if(applicationContext == null){
            log.error("getEnvironmentVariable  applicationContext is null");
            return defaultValue;
        }
        Environment environment = applicationContext.getEnvironment();
        String value = environment.getProperty(key);
        return Objects.isNull(value) ? defaultValue : value;
    }

    public static String getEnvironmentVariable(String ... keys) {
        if(applicationContext == null){
            log.error("getEnvironmentVariable  applicationContext is null");
            return null;
        }

        Environment environment = applicationContext.getEnvironment();
        if(keys.length == 1){
            return environment.getProperty(keys[0]);
        }
        StringBuilder value = new StringBuilder();
        for (String key : keys) {
            value.append(environment.getProperty(key));
        }
        return value.toString();
    }
}
